<?php 
namespace app\wework\model\user\qr;
use think\facade\Db;
use think\facade\Session;
use app\wework\model\QyWechatApi;

/**
* 配置类
**/
class QrModel {

	static public $wid;
	/**
	 * 获取用户列表数据
	 * @param $wid 账户id
	 * @param $data 接受的数据
	 * @return 
	 */
	static public function group(){
		self::iniSetGroup();
		$wid = Session::get('wid');
		$res = Db::table('kt_wework_qrgroup')
			   ->alias('g')
			   ->field('g.id,g.name,count(q.id) as qr_number')
			   ->leftjoin('kt_wework_qr q','g.id=q.groupid')
			   ->where('g.wid',$wid)
			   ->group('id')
			   ->select();
		return $res;
	}
	/**
	 * 获取用户列表数据
	 * @param $wid 账户id
	 * @param $data 接受的数据
	 * @return 
	 */
	static public function popGroup(){
		self::iniSetGroup();
		$data = [];
		$wid = Session::get('wid');
		$data['item'] = Db::table('kt_wework_qrgroup')
			   ->alias('g')
			   ->field('g.id,g.name,count(q.id) as qr_number')
			   ->leftjoin('kt_wework_qr q','g.id=q.groupid')
			   ->where('g.wid',$wid)
			   ->filter(function($r){
			   		$r['haschilden']=$r['qr_number'] > 0 ? true : false;
			   		$r['childen'] = Db::table('kt_wework_qr')->where('groupid',$r['id'])->column('id,name');
			   		return $r;
			   })
			   ->group('id')
			   ->select();
		$data['qr_number'] = Db::table('kt_wework_qr')->where('wid',$wid)->count();
		return $data;
	}
	/**
	 * 获取渠道活码列表
	 * @param where array|string 
	 * @param page 页码
   	 * @param size 每页条数
	 * @return 
	 */
 	static public function list($where=[], $page=1, $size=10){
 		$wid = Session::get('wid');
 		$where["wid"] = $wid;
		$res = Db::table('kt_wework_qr')
		      ->field('id,name,qr_code,create_time,staffid,staff_type,staffup_status,staff_data,staff_standby,tag,tag_status')
		      ->json(['staffid','staff_data','staff_standby','tag'])
		      ->where($where)
		      ->filter(function($qr){
		        $qr['scan_number'] = Db::table('kt_wework_scan_log')->where(['pid'=>$qr['id']])->count();
		        $qr['staffname'] = self::staffData($qr);
		        $qr['staff_standby_name'] = Db::table('kt_wework_staff')->where(['id'=>$qr['staff_standby']])->column('name');
		        $qr['tag_name'] = $qr['tag_status'] ? Db::table('kt_wework_tag')->where(['tag_id'=>$qr['tag']])->column('tag_name'):[];
		        return $qr;
		      });
		$data['count'] = $res->count();
		$data['item'] = $res->order('create_time desc')->page($page,$size)->select();
		$data['page'] = $page;
		$data['size'] = $size;
		return $data;

	}

	static public function tags($tag){
		$res = Db::table('kt_wework_tag')->where(['tag_id'=>$tag])->field('tag_name,tag_id')->select()->toArray();

		return $res;
	}

	static public function infos(){
		$wid = Session::get('wid');
 		$where["wid"] = $wid;
 		$res = Db::table('kt_wework_qr')
		      ->field('id,name')
		      ->where($where)
		      ->select()
		      ->toArray();

		return $res;
	}

	static public function staffData($qr){
      $show = [];
      switch ($qr['staff_type']) {
        case '1':
          $show = $qr['staffid'];
          break;
        case '2':
          $week = date('w');
          foreach ($qr['staff_data'] as $v) {
            $sWeekArr = explode(',', $v['week']);
            if(in_array($week, $sWeekArr) && time() >= strtotime($v['startime']) && time() <= strtotime($v['endtime'])){
               $show = array_merge($show,$v['staffid']);
            }
          }
          break;
      }
      $staffname =  Db::table('kt_wework_staff')->where(['id'=>$show])->filter(function($staff){
        $staff['show'] = true;
        return $staff;
      })->column('id,name');
      $notshow = array_diff($qr['staffid'], $show);
      $notStaffname =  $notshow ? Db::table('kt_wework_staff')->where(['id'=>$notshow])->filter(function($staff){
        $staff['show'] = false;
        return $staff;
      })->column('id,name') : [];

      return array_merge($staffname,$notStaffname);
    } 

    /**
	 * 获取渠道活码列表
	 * @param id array|int  渠道id
	 * @param page 页码
   	 * @param size 每页条数
	 * @return 
	 */
 	static public function listById($id,$page=1, $size=10,$wid=NULL){
 		$wid = Session::get('wid')?:$wid;
 		$id = $id ?: Db::table('kt_wework_qr')->where('wid',$wid)->order('create_time desc')->limit(1)->value('id');
 		$data = [];
		$res = Db::table('kt_wework_qr')
		      ->field('id,wid,name,groupid,merge_qr_code,state,create_time')
		      ->where(['wid'=>$wid,'id'=>$id])
			  ->filter(function($qr){
		        $qr['groupname'] = Db::table('kt_wework_qrgroup')->where('id',$qr['groupid'])->value('name');
		        $qr['today_add_number'] = Db::table('kt_wework_customer')->where(['status'=>0,'state'=>$qr['state']])->whereDay('createtime')->count();
		        $qr['today_lossing_number'] = Db::table('kt_wework_customer')->where('status','>',0)->where('state',$qr['state'])->whereDay('createtime')->count();
		        $qr['total_add_number'] = Db::table('kt_wework_customer')->where(['status'=>0,'state'=>$qr['state']])->count();
		        $qr['total_lossing_number'] = Db::table('kt_wework_customer')->where('status','>',0)->where('state',$qr['state'])->count();

		        return $qr;
		      });
		$data['count'] = $res->count();
		$data['item'] = $res->order('create_time desc')->page($page,$size)->select();
		$data['page'] = $page;
		$data['size'] = $size;
		return $data;

	}
	/**
	 * 统计信息  图表
	 * @param  id array 渠道id
	 * @return 返回更新条数
	 */
	static public function  statisticsStaff($id){
		$wid = Session::get('wid');
		// $end = 1;
		$data = [];
		$qr = Db::table('kt_wework_qr')
		      ->field('id,staffid,staff_type,staffup_status,staff_data,staff_standby')
		      ->json(['staffid','staff_data','staff_standby'])
		      ->where(['wid'=>$wid,'id'=>$id])
		      // ->filter(function($qr)use ($wid,$end){
		      //   $qr['staffname'] = self::staffData($qr);
		      //   return $qr;
		      // })
		      ->select()
		      ->toArray();
		$staffidArr =  array_unique(array_reduce(array_column($qr, 'staffid'), 'array_merge',array()));
		$res = Db::table('kt_wework_staff')->field('id,name,avatar')->where('id','in',$staffidArr)->select();

		return $res;
	}
	/**
	 * 统计信息  表格
	 * @param  id array|int 渠道id
	 * @param  type array 类型 total总人数  new新增 lossing流失
	 * @param  date array 渠道id
	 * @return 返回更新条数
	 */
	static public function statisticsTable($id,$type,$date,$staff_id,$wid=NULL){
		$data = [];
		$wid = Session::get('wid')?:$wid;
		$state = Db::table('kt_wework_qr')->where(['id'=>$id])->column('state');
		if($staff_id)$where[]=['staff_id','=',$staff_id];
		$where = [['wid','=',$wid],['state','in',$state]];
		switch ($type) {
			case 'date':
				for ($i=0; $i < count($date); $i++) { 
					$date[$i]['total_number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where($where)->whereTime('createtime','<',$date[$i]['date']." 23:59:59")->count();
					$date[$i]['new_number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where($where)->where('status',0)->whereDay('createtime',$date[$i]['date'])->count();
					$date[$i]['lossing_number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where($where)->where('status','>',0)->whereDay('createtime',$date[$i]['date'])->count();
				}
				return $date;
				break;
			case 'staff':
				$end = $date[count($date)-1]['date'] . " 23:59:59";
				$staff = Db::table('kt_wework_customer')
					   ->alias('c')
			   		   ->field('c.staff_id,s.name,count(c.staff_id) as total_number')
					   ->leftjoin('kt_wework_staff s','c.staff_id=s.id')
					   ->whereTime('createtime','<',$end)
					   ->where(['c.state'=>$state])
					   ->group('staff_id')
					   ->select()
					   ->toArray();
				foreach ($staff as &$s) {
					$s['new_number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where(['staff_id'=>$s['staff_id'],'state'=>$state])->where('status',0)->whereTime('createtime','<',$end)->count();
					$s['lossing_number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where(['staff_id'=>$s['staff_id'],'state'=>$state])->where('status','>',0)->whereTime('createtime','<',$end)->count();
				}
				return $staff;
				break;
		}
		
		return $date;
	}
	/**
	 * 统计信息  图表
	 * @param  id array|int 渠道id
	 * @param  type array 类型 total总人数  new新增 lossing流失
	 * @param  date array 渠道id
	 * @return 返回更新条数
	 */
	static public function statisticsChar($id,$type,$date,$staff_id){
		$data = [];
		$wid = Session::get('wid');
		$state = Db::table('kt_wework_qr')->where(['id'=>$id])->column('state');
		if($staff_id)$where[]=['staff_id','=',$staff_id];
		$where = [['wid','=',$wid],['state','in',$state]];
		switch ($type) {
			case 'total':
				$where[]=['status','=',0];
				for ($i=0; $i < count($date); $i++) { 
					$date[$i]['number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where($where)->whereTime('createtime','<',$date[$i]['date']." 23:59:59")->count();
				}
				break;
			case 'new':
				$where[]=['status','=',0];
				for ($i=0; $i < count($date); $i++) { 
					$date[$i]['number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where($where)->whereDay('createtime',$date[$i]['date'])->count();
				}
				break;
			case 'lossing':
				$where[]=['status','>',0];
				for ($i=0; $i < count($date); $i++) { 
					$date[$i]['number'] = Db::table('kt_wework_customer')->distinct(true)->field('external_userid')->where($where)->whereDay('createtime',$date[$i]['date'])->count();
				}
				break;
		}
		
		return $date;
	}
	/**
	 * 日期
	 * @param  id array|int 渠道id
	 * @return 返回更新条数
	 */
	static public function getStatisticsDate($date_type,$startime=null,$endtim=null){
		$data = [];
		switch ($date_type) {
			case 'day':
				$data[] = ['date' => date("Y-m-d")];
				break;
			case 'week':
				for ($i=6; $i >= 0; $i--) { 
					$data[] = ['date'=>date("Y-m-d",strtotime("-$i day"))];
				}
				break;
			case 'mouth':
				for ($i=29; $i >= 0; $i--) { 
					$data[] = ['date'=>date("Y-m-d",strtotime("-$i day"))];
				}
				break;
			case 'self':
				$star = strtotime($startime);
				$end = strtotime($endtim);
				while ($star <= $end) {
					$data[] = ['date'=>date("Y-m-d",$star)];
					$star += 3600*24;
				}
				break;
		}

		return $data;
	}
	/**
	 * 统计信息 图表
	 * @param  id array|int 渠道id
	 * @return 返回更新条数
	 */
	static public function statisticsInfo($id){
		$data = [];
		$wid = Session::get('wid');
		$state = Db::table('kt_wework_qr')->where(['id'=>$id])->column('state');
		$data['today_add_number'] = Db::table('kt_wework_customer')->where(['status'=>0,'state'=>$state])->whereDay('createtime')->count();
		$data['today_lossing_number'] = Db::table('kt_wework_customer')->where('status','>',0)->where(["state"=>$state])->whereDay('createtime')->count();
		$data['total_add_number'] = Db::table('kt_wework_customer')->where(['status'=>0,'state'=>$state])->count();
		$data['total_lossing_number'] =Db::table('kt_wework_customer')->where('status','>',0)->where(["state"=>$state])->count();

		return $data;
	}
	/**
	 * 更新|添加 save
	 * @param data 数据 
	 * @return 返回更新条数
	 */
	static public function save($data,$jsonfield=[],$url=NULL){
		$apiData = ['scene'=>2];
		if($data['skipverify_status']){
			if($data['skipverify_type'] == 1){
				$apiData['skip_verify'] = true;
			}else{
				$time = time();
				$apiData['skip_verify'] = (strtotime($data['skipverify_time'][0]) <= $time && $time <= strtotime($data['skipverify_time'][1])) ? true : false;
			}
		}else{
			$apiData['skip_verify'] = false;
		}
		$apiStaffid = [];
		if($data['staff_type'] == 1){
			$apiStaffid = $data['staffid'];
		}else{
			$week = date('w');
			$staffid = [];
			foreach ($data['staff_data'] as $s) {
				$sWeekArr = explode(',', $s['week']);
				$staffid = array_merge($staffid,$s['staffid']);
				if(in_array($week, $sWeekArr) && date("H:i") >= $s['startime'] && date("H:i") <= $s['endtime']){
					$apiStaffid = array_merge($apiStaffid,$s['staffid']);
				}
			}
			if(count($apiStaffid) == 0) $apiStaffid = $data['staff_standby'];
			$data["staffid"] = $staffid;
		}
		$apiData['user'] = Db::table('kt_wework_staff')->where(['id'=>$apiStaffid])->column('userid');
		$data['type'] = $apiData['type'] = count($apiStaffid) > 1 ? 2 : 1;
		if(isset($data['id']) && $data['id']){
			$qr = Db::table('kt_wework_qr')->find($data['id']);
			$qrCode = $qr['merge_qr_code'];
			$apiData['config_id'] = $qr['config_id'];
			$apiRes = QyWechatApi::updateContactWay($apiData);
			if($apiRes['errcode'] != 0) return error('添加失败');
		}else{
			$data['state'] = $apiData['state'] = 'qr' . (Db::table('kt_wework_qr')->max('id')+1);
			$apiRes = QyWechatApi::addContactWay($apiData);
			if($apiRes['errcode'] != 0) return error('添加失败');
			$data['create_time'] = date("Y-m-d H:i:s");
			$data['config_id'] = $apiRes['config_id'];
			$qrCode = $data['qr_code'] = $apiRes['qr_code'];
		}
		
		$data['update_time'] = date("Y-m-d H:i:s");
		if($data['image']){
			$mergeQrCodeLocalPath = public_path().'upload/wework/'.basename($data['image']);
			$imageRes = createPoster($mergeQrCodeLocalPath,$qrCode,$data['image']);
			$mergeQrCodeLocalPath = $url.'/upload/wework/'.basename($data['image']);
			$data['merge_qr_code'] = $imageRes ? $mergeQrCodeLocalPath : $qrCode;
		} else{
			$data['merge_qr_code'] = $qrCode;
		}
		$res = Db::table('kt_wework_qr')->json($jsonfield)->save($data);
		return success("添加成功");
	}

	/**
	 * 初始化分组数据, 添加一个默认分组
	 * @return 
	 */
	static private function inisetGroup(){
		$wid = Session::get('wid');
		$group = Db::table('kt_wework_qrgroup')->where('wid',$wid)->where('name','默认分组')->find();
		if(!$group){
			Db::table('kt_wework_qrgroup')->insert(
			 	[
			 		'wid' => $wid,
			 		'name' => '默认分组',
			 		'create_time'=>date("Y-m-d H:i:s"),
			 		'update_time'=>date("Y-m-d H:i:s"),
			 	]
			);
		} 
	}
}